import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Table,
  Card,
  Button,
  Input,
  Select,
  Space,
  Avatar,
  Tag,
  Tooltip,
  Modal,
  message,
  Dropdown,
  Typography,
  Row,
  Col,
  InputNumber,
  Switch,
  Collapse,
} from 'antd';
import {
  PlusOutlined,
  EyeOutlined,
  EditOutlined,
  DeleteOutlined,
  MessageOutlined,
  DownloadOutlined,
  UploadOutlined,
  MoreOutlined,
  UserOutlined,
  SearchOutlined,
  DownOutlined,
} from '@ant-design/icons';
import type { ColumnsType, TableProps } from 'antd/es/table';
import { UserProfile, QueryUserprofileRequest } from '@/types';
import { formatDate, getAvatarUrl } from '@/utils';
import { userAPI } from '@/services/api';
import NewUserForm from './NewUserForm';


const { Option } = Select;
const { Text } = Typography;
const { Panel } = Collapse;

const UserList: React.FC = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [users, setUsers] = useState<UserProfile[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
  const [filters, setFilters] = useState<QueryUserprofileRequest>({});
  const [showNewUserForm, setShowNewUserForm] = useState(false);
  const [advancedSearchOpen, setAdvancedSearchOpen] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 20,
    total: 0,
  });

  const getStatusTag = (maritalStatus: string) => {
    const statusMap = {
      '未婚': { color: 'green', text: '未婚' },
      '离异': { color: 'orange', text: '离异' },
      '丧偶': { color: 'red', text: '丧偶' },
    };
    const config = statusMap[maritalStatus as keyof typeof statusMap] || { color: 'gray', text: maritalStatus };
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  const columns: ColumnsType<UserProfile> = [
    {
      title: '用户信息',
      key: 'userInfo',
      width: 200,
      render: (_, record) => (
        <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
          <Avatar
            size={48}
            src={getAvatarUrl(undefined, record.gender === '男' ? 'male' : 'female')}
            icon={<UserOutlined />}
          />
          <div>
            <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
              <Text strong>{record.name}</Text>
            </div>
            <div style={{ fontSize: '12px', color: '#8c8c8c' }}>
              {record.age}岁 • {record.gender}
            </div>
            <div style={{ fontSize: '12px', color: '#8c8c8c' }}>
              编号: {record.userNum}
            </div>
          </div>
        </div>
      ),
    },
    {
      title: '基本信息',
      key: 'basicInfo',
      width: 150,
      render: (_, record) => (
        <div>
          <div>{record.height}cm / {record.weight}斤</div>
          {record.bmiDesc && <div style={{ fontSize: '12px', color: '#8c8c8c' }}>{record.bmiDesc}</div>}
        </div>
      ),
    },
    {
      title: '婚姻状态',
      key: 'maritalStatus',
      width: 100,
      render: (_, record) => getStatusTag(record.maritalStatus),
    },
    {
      title: '学历',
      dataIndex: 'education',
      key: 'education',
      width: 80,
    },
    {
      title: '收入',
      key: 'income',
      width: 100,
      render: (_, record) => (
        <span>{record.assets?.annualIncome || 0}万</span>
      ),
    },
    {
      title: '职业',
      dataIndex: 'occupation',
      key: 'occupation',
      width: 120,
    },
    {
      title: '籍贯',
      dataIndex: 'hometown',
      key: 'hometown',
      width: 120,
    },
    {
      title: '常住地',
      dataIndex: 'currentResidence',
      key: 'currentResidence',
      width: 120,
    },
    {
      title: '生日',
      key: 'birthDate',
      width: 120,
      render: (_, record) => formatDate(record.birthDate, 'YYYY-MM-DD'),
    },
    {
      title: '属相',
      dataIndex: 'chineseZodiac',
      key: 'chineseZodiac',
      width: 80,
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: 150,
      render: (_, record) => (
        <Space>
          <Tooltip title="查看详情">
            <Button 
              type="text" 
              icon={<EyeOutlined />} 
              onClick={() => handleViewUser(record.userNum)}
            />
          </Tooltip>

          <Dropdown
            menu={{
              items: [
                {
                  key: 'message',
                  icon: <MessageOutlined />,
                  label: '发送通知',
                },
                {
                  key: 'offline',
                  icon: <DeleteOutlined />,
                  label: '强制下线',
                  danger: true,
                },
              ],
            }}
            trigger={['click']}
          >
            <Button type="text" icon={<MoreOutlined />} />
          </Dropdown>
        </Space>
      ),
    },
  ];

  const handleSearch = async () => {
    try {
      console.log('开始加载用户列表...');
      console.log('筛选条件:', filters);
      setLoading(true);
      
      // 构建请求参数，包括分页参数
      const requestParams = {
        ...filters,
        pageNum: pagination.current,
        pageSize: pagination.pageSize,
      };
      
      console.log('调用API前的参数:', requestParams);
      const response = await userAPI.getUserProfileList(requestParams);
      console.log('API响应完整数据:', response);
      console.log('响应类型:', typeof response);
      console.log('响应code:', response?.code);
      console.log('响应data:', response?.data);
      
      if (response && response.code === 0) {
        const userData = response.data as any;
        console.log('设置用户数据:', userData.userprofileList);
        setUsers(userData.userprofileList);
        setPagination(prev => ({ 
          ...prev, 
          total: userData.totalNum 
        }));
        console.log('用户数据加载成功，共', userData.userprofileList.length, '条');
      } else {
        console.error('API返回错误:', response);
        message.error((response as any)?.msg || '获取数据失败');
      }
    } catch (error) {
      console.error('加载用户列表失败:', error);
      console.error('错误详情:', error);
      message.error('加载数据失败');
    } finally {
      setLoading(false);
    }
  };

  const handleTableChange: TableProps<UserProfile>['onChange'] = (paginationConfig) => {
    const newPagination = {
      current: paginationConfig.current || 1,
      pageSize: paginationConfig.pageSize || 20,
      total: paginationConfig.total || 0,
    };
    setPagination(newPagination);
    
    // 分页变化时重新查询
    setTimeout(() => {
      handleSearch();
    }, 0);
  };

  const handleBatchAction = (action: string) => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择要操作的用户');
      return;
    }

    Modal.confirm({
      title: `确定要对 ${selectedRowKeys.length} 个用户执行${action}操作吗？`,
      onOk: () => {
        message.success(`批量${action}操作成功`);
        setSelectedRowKeys([]);
      },
    });
  };

  const handleExport = () => {
    message.info('正在导出数据...');
    // 模拟导出
    setTimeout(() => {
      message.success('导出成功');
    }, 2000);
  };

  const handleNewUserSuccess = () => {
    setShowNewUserForm(false);
    // 刷新用户列表
    handleSearch();
  };

  const handleViewUser = (userNum: number) => {
    navigate(`/user/detail/${userNum}`);
  };



  useEffect(() => {
    console.log('UserList组件已挂载，开始初始化数据...');
    handleSearch();
  }, []);

  return (
    <div className="page-container">
      <div className="page-header">
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
          <div>
            <h2 className="page-title">用户档案列表</h2>
            <p className="page-description">
              管理平台所有用户档案信息，支持筛选、搜索和批量操作
            </p>
          </div>
          <Space>
            <Button icon={<UploadOutlined />}>
              导入Excel
            </Button>
            <Button type="primary" icon={<PlusOutlined />} onClick={() => setShowNewUserForm(true)}>
              新增用户
            </Button>
          </Space>
        </div>
      </div>

      {/* 搜索区域 */}
      <Card style={{ marginBottom: '24px' }} bodyStyle={{ padding: '24px' }}>
        {/* 基础搜索 */}
        <div style={{ marginBottom: '20px' }}>
          <Row gutter={[16, 16]} align="middle">
            <Col xs={24} sm={8} md={4}>
              <Input
                placeholder="用户编号"
                value={filters.userNumList?.[0]}
                onChange={(e) => setFilters({ 
                  ...filters, 
                  userNumList: e.target.value ? [parseInt(e.target.value)] : undefined 
                })}
                onPressEnter={handleSearch}
                prefix={<UserOutlined />}
              />
            </Col>
            <Col xs={24} sm={8} md={3}>
              <Select
                placeholder="性别"
                value={filters.gender}
                onChange={(value) => setFilters({ ...filters, gender: value })}
                allowClear
                style={{ width: '100%' }}
              >
                <Option value="男">男</Option>
                <Option value="女">女</Option>
              </Select>
            </Col>
            <Col xs={24} sm={8} md={3}>
              <Select
                placeholder="婚姻状态"
                value={filters.maritalStatus}
                onChange={(value) => setFilters({ ...filters, maritalStatus: value })}
                allowClear
                style={{ width: '100%' }}
              >
                <Option value="未婚">未婚</Option>
                <Option value="离异">离异</Option>
                <Option value="丧偶">丧偶</Option>
              </Select>
            </Col>
            <Col xs={24} sm={8} md={4}>
              <Space.Compact style={{ width: '100%' }}>
                <InputNumber
                  placeholder="最小年龄"
                  min={18}
                  max={100}
                  value={filters.ageRange?.minAge}
                  onChange={(value) => setFilters({ 
                    ...filters, 
                    ageRange: { ...filters.ageRange, minAge: value || undefined }
                  })}
                  style={{ width: '50%' }}
                />
                <InputNumber
                  placeholder="最大年龄"
                  min={18}
                  max={100}
                  value={filters.ageRange?.maxAge}
                  onChange={(value) => setFilters({ 
                    ...filters, 
                    ageRange: { ...filters.ageRange, maxAge: value || undefined }
                  })}
                  style={{ width: '50%' }}
                />
              </Space.Compact>
            </Col>
            <Col xs={24} sm={8} md={4}>
              <Space.Compact style={{ width: '100%' }}>
                <InputNumber
                  placeholder="最低身高(cm)"
                  min={100}
                  max={250}
                  value={filters.heightRange?.minHeight}
                  onChange={(value) => setFilters({ 
                    ...filters, 
                    heightRange: { ...filters.heightRange, minHeight: value || undefined }
                  })}
                  style={{ width: '50%' }}
                />
                <InputNumber
                  placeholder="最高身高(cm)"
                  min={100}
                  max={250}
                  value={filters.heightRange?.maxHeight}
                  onChange={(value) => setFilters({ 
                    ...filters, 
                    heightRange: { ...filters.heightRange, maxHeight: value || undefined }
                  })}
                  style={{ width: '50%' }}
                />
              </Space.Compact>
            </Col>
            <Col xs={24} sm={8} md={5}>
              {!advancedSearchOpen ? (
                <Space>
                  <Button type="primary" icon={<SearchOutlined />} onClick={handleSearch} loading={loading}>
                    搜索
                  </Button>
                  <Button onClick={() => setFilters({})}>
                    重置
                  </Button>
                  <Button 
                    type="default" 
                    icon={<DownOutlined />} 
                    onClick={() => setAdvancedSearchOpen(true)}
                  >
                    高级搜索
                  </Button>
                </Space>
              ) : (
                <Button 
                  type="default" 
                  icon={<DownOutlined style={{ transform: 'rotate(180deg)' }} />} 
                  onClick={() => setAdvancedSearchOpen(false)}
                >
                  收起
                </Button>
              )}
            </Col>
          </Row>
        </div>

        {/* 高级搜索 */}
        <Collapse 
          activeKey={advancedSearchOpen ? ['advanced'] : []} 
          ghost 
          bordered={false}
          onChange={(key) => setAdvancedSearchOpen(key.includes('advanced'))}
          style={{ marginTop: '20px' }}
        >
          <Panel 
            header={<Text strong>高级搜索选项</Text>} 
            key="advanced" 
            showArrow={false}
            style={{ padding: 0 }}
          >
            <div style={{ padding: '16px 0', borderTop: '1px solid #f0f0f0' }}>
              <Row gutter={[16, 16]}>
                {/* 体重范围 */}
                <Col xs={24} sm={12} md={6}>
                  <div style={{ marginBottom: '8px' }}>
                    <Text type="secondary">体重范围(斤)</Text>
                  </div>
                  <Space.Compact style={{ width: '100%' }}>
                    <InputNumber
                      placeholder="最低"
                      min={50}
                      max={300}
                      value={filters.weightRange?.minWeight}
                      onChange={(value) => setFilters({ 
                        ...filters, 
                        weightRange: { ...filters.weightRange, minWeight: value || undefined }
                      })}
                      style={{ width: '50%' }}
                    />
                    <InputNumber
                      placeholder="最高"
                      min={50}
                      max={300}
                      value={filters.weightRange?.maxWeight}
                      onChange={(value) => setFilters({ 
                        ...filters, 
                        weightRange: { ...filters.weightRange, maxWeight: value || undefined }
                      })}
                      style={{ width: '50%' }}
                    />
                  </Space.Compact>
                </Col>

                {/* 年收入范围 */}
                <Col xs={24} sm={12} md={6}>
                  <div style={{ marginBottom: '8px' }}>
                    <Text type="secondary">年收入范围(万元)</Text>
                  </div>
                  <Space.Compact style={{ width: '100%' }}>
                    <InputNumber
                      placeholder="最低"
                      min={0}
                      step={0.1}
                      value={filters.incomeRange?.minIncome}
                      onChange={(value) => setFilters({ 
                        ...filters, 
                        incomeRange: { ...filters.incomeRange, minIncome: value || undefined }
                      })}
                      style={{ width: '50%' }}
                    />
                    <InputNumber
                      placeholder="最高"
                      min={0}
                      step={0.1}
                      value={filters.incomeRange?.maxIncome}
                      onChange={(value) => setFilters({ 
                        ...filters, 
                        incomeRange: { ...filters.incomeRange, maxIncome: value || undefined }
                      })}
                      style={{ width: '50%' }}
                    />
                  </Space.Compact>
                </Col>

                {/* 学历范围 */}
                <Col xs={24} sm={12} md={6}>
                  <div style={{ marginBottom: '8px' }}>
                    <Text type="secondary">学历范围</Text>
                  </div>
                  <Space.Compact style={{ width: '100%' }}>
                    <Select
                      placeholder="最低学历"
                      value={filters.educationRange?.minEducation}
                      onChange={(value) => setFilters({ 
                        ...filters, 
                        educationRange: { ...filters.educationRange, minEducation: value }
                      })}
                      allowClear
                      style={{ width: '50%' }}
                    >
                      <Option value="小学">小学</Option>
                      <Option value="初中">初中</Option>
                      <Option value="高中">高中</Option>
                      <Option value="中专">中专</Option>
                      <Option value="职高">职高</Option>
                      <Option value="技校">技校</Option>
                      <Option value="大专">大专</Option>
                      <Option value="本科">本科</Option>
                      <Option value="硕士">硕士</Option>
                      <Option value="博士">博士</Option>
                      <Option value="博士后">博士后</Option>
                    </Select>
                    <Select
                      placeholder="最高学历"
                      value={filters.educationRange?.maxEducation}
                      onChange={(value) => setFilters({ 
                        ...filters, 
                        educationRange: { ...filters.educationRange, maxEducation: value }
                      })}
                      allowClear
                      style={{ width: '50%' }}
                    >
                      <Option value="小学">小学</Option>
                      <Option value="初中">初中</Option>
                      <Option value="高中">高中</Option>
                      <Option value="中专">中专</Option>
                      <Option value="职高">职高</Option>
                      <Option value="技校">技校</Option>
                      <Option value="大专">大专</Option>
                      <Option value="本科">本科</Option>
                      <Option value="硕士">硕士</Option>
                      <Option value="博士">博士</Option>
                      <Option value="博士后">博士后</Option>
                    </Select>
                  </Space.Compact>
                </Col>

                {/* 所在行业 */}
                <Col xs={24} sm={12} md={6}>
                  <div style={{ marginBottom: '8px' }}>
                    <Text type="secondary">所在行业</Text>
                  </div>
                  <Input
                    placeholder="输入行业关键词"
                    value={filters.occupation}
                    onChange={(e) => setFilters({ ...filters, occupation: e.target.value })}
                    onPressEnter={handleSearch}
                  />
                </Col>

                {/* 籍贯要求 */}
                <Col xs={24} sm={12} md={6}>
                  <div style={{ marginBottom: '8px' }}>
                    <Text type="secondary">籍贯要求</Text>
                  </div>
                  <Select
                    mode="multiple"
                    placeholder="选择籍贯"
                    value={filters.hometownPreference}
                    onChange={(value) => setFilters({ ...filters, hometownPreference: value })}
                    allowClear
                    style={{ width: '100%' }}
                    maxTagCount={2}
                  >
                    <Option value="广德">广德</Option>
                    <Option value="郎溪">郎溪</Option>
                    <Option value="宁国">宁国</Option>
                    <Option value="宣城">宣城</Option>
                  </Select>
                </Col>

                {/* 工作地要求 */}
                <Col xs={24} sm={12} md={6}>
                  <div style={{ marginBottom: '8px' }}>
                    <Text type="secondary">工作地要求</Text>
                  </div>
                  <Select
                    mode="multiple"
                    placeholder="选择工作地"
                    value={filters.currentResidencePreference}
                    onChange={(value) => setFilters({ ...filters, currentResidencePreference: value })}
                    allowClear
                    style={{ width: '100%' }}
                    maxTagCount={2}
                  >
                    <Option value="上海">上海</Option>
                    <Option value="杭州">杭州</Option>
                    <Option value="合肥">合肥</Option>
                    <Option value="北京">北京</Option>
                    <Option value="南京">南京</Option>
                    <Option value="芜湖">芜湖</Option>
                  </Select>
                </Col>

                {/* 父母退休金 */}
                <Col xs={24} sm={12} md={6}>
                  <div style={{ marginBottom: '8px' }}>
                    <Text type="secondary">父母有退休金</Text>
                  </div>
                  <Switch
                    checked={filters.parentsHasPension}
                    onChange={(checked) => setFilters({ ...filters, parentsHasPension: checked })}
                    checkedChildren="是"
                    unCheckedChildren="否"
                  />
                </Col>
              </Row>
              
              {/* 搜索按钮区域 - 只在高级搜索展开时显示 */}
              <div style={{ marginTop: '24px', textAlign: 'center', borderTop: '1px solid #f0f0f0', paddingTop: '16px' }}>
                <Space size="large">
                  <Button type="primary" icon={<SearchOutlined />} onClick={handleSearch} loading={loading} size="large">
                    搜索
                  </Button>
                  <Button onClick={() => setFilters({})} size="large">
                    重置所有筛选
                  </Button>
                </Space>
              </div>
            </div>
          </Panel>
        </Collapse>
      </Card>

      {/* 工具栏 */}
      <div className="toolbar">
        <div className="toolbar-left">
          <Space>
            <Button onClick={() => handleBatchAction('发送消息')} disabled={selectedRowKeys.length === 0}>
              批量发送消息
            </Button>
            <Button onClick={() => handleBatchAction('下线')} disabled={selectedRowKeys.length === 0}>
              批量下线
            </Button>
          </Space>
          {selectedRowKeys.length > 0 && (
            <Text type="secondary">已选择 {selectedRowKeys.length} 项</Text>
          )}
        </div>
        <div className="toolbar-right">
          <Space>
            <Button icon={<DownloadOutlined />} onClick={handleExport}>
              导出选中
            </Button>
          </Space>
        </div>
      </div>

      {/* 用户表格 */}
      <Card>
        <Table
          columns={columns}
          dataSource={users}
          rowKey="userNum"
          loading={loading}
          pagination={{
            ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) =>
              `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
          }}
          scroll={{ x: 1200 }}
          rowSelection={{
            selectedRowKeys,
            onChange: (keys) => setSelectedRowKeys(keys as number[]),
            type: 'checkbox',
          }}
          onChange={handleTableChange}
        />
      </Card>

      {/* 新增用户表单 */}
      <NewUserForm
        visible={showNewUserForm}
        onCancel={() => setShowNewUserForm(false)}
        onSuccess={handleNewUserSuccess}
      />
    </div>
  );
};

export default UserList;